import style from "./index.module.scss";
import Card from "../../../components/Card";
import { useDebounceFn } from "ahooks";
import { FC, useRef } from "react";
import { Spin, Skeleton } from "antd";
import { useState, useEffect } from "react";
import { produce } from "immer";
import useMouse from "../../../hooks/useMouse";
import useTitle from "../../../hooks/useTitle";
import { Button } from "antd";
import request from "@/utils/request";
import { api } from "@/api";
import SearchInput from "@/components/SearchInput/index";
import { Typography } from "antd";
import { useRouteParams } from "@/hooks/useRouteParams";
import { useHandRouterChange } from "@/hooks/useHandRouterChange";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { get } from "http";

const { Title } = Typography;

// 定义问卷数据的类型
interface Questionnaire {
  id: string;
  delete: boolean;
  title: string;
  published: boolean;
  star: boolean;
  time: Date;
  answerCount?: number;
  deleted?: boolean;
}

const List: FC = () => {
  const searchParams = useRouteParams("keyWord");
  const [questionList, setQuesionList] = useState<Questionnaire[]>([]);
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const haveMore = total > questionList.length;

  const getList = async () => {
    const res = await api.questionnaire.getQuestionnaireList();
    console.log("获取问卷列表", res);
    setQuesionList(res.data);
  };
  // 查询参数改变自动获取数据
  const { loading, data } = useHandRouterChange(
    api.questionnaire.getQuestionnaireList,
    "keyWord",
  );
  useEffect(() => {
    console.log("获取问卷列表", data);
    if (data) {
      setQuesionList(data);
      setTotal(data?.total);
    }
  }, [data]);

  //触发加载
  const onLoadMore = async () => {
    const domRect = loadRef.current?.getBoundingClientRect();
    if (domRect && domRect.bottom <= document.documentElement.clientHeight) {
      console.log("加载更多");
      const {
        data: { list, total: listTotal },
      } = await api.questionnaire.getQuestionnaireList();
      setQuesionList(questionList.concat(list));
      setTotal(listTotal + list.length);
    }
  };
  //防抖
  const containerRef = useRef<HTMLDivElement>(null);
  const loadRef = useRef<HTMLDivElement>(null);
  const { run: abc } = useDebounceFn(onLoadMore, { wait: 100 });
  const test = () => {
    console.log("test");
  };
  useEffect(() => {
    useTitle("我的问卷");
    window.addEventListener("scroll", abc);
    return () => {
      window.removeEventListener("scroll", abc);
    };
  }, []);

  //添加问卷
  const add = () => {
    const sel = Math.random().toString().slice(-3);
    // setQuesionList([
    //   ...questionList,
    //   {
    //     id: "q" + sel,
    //     title: "问卷" + sel,
    //     isPublished: false,
    //   },
    // ]);
    setQuesionList(
      produce((draft) => {
        draft.push({
          id: "q" + sel,
          title: "问卷" + sel,
          isPublished: false,
          isStar: false,
        });
      }),
    );
  };
  //是否标星
  const handStar = async (id: string, starState: boolean) => {
    const res = await api.questionnaire.putQuestionnaire({
      id,
      isStar: starState,
    });
    console.log("修改标星响应", res);
    getList();
  };
  const delQuestionList = async (id: string) => {
    console.log("删除问卷", id);
    // // setQuesionList(
    // //   questionList.filter((item) => {
    // //     if (id == item.id) return false;
    // //     else return true;
    // //   }),
    // // );
    // const index = questionList.findIndex((item) => item.id == id);
    // setQuesionList(
    //   produce((item) => {
    //     item.splice(index, 1);
    //   }),
    // );
    const res = await api.questionnaire.putQuestionnaire({
      id,
      isDeleted: true,
    });
    getList();
  };
  //发布问卷
  const edit = (id: string) => {
    console.log(id);
    setQuesionList(
      questionList.map((item) => {
        if (item.id == id) {
          return { ...item, isPublished: true };
        } else return item;
      }),
    );
    // setQuesionList(
    //   produce((arr) => {
    //     const q = arr.find((item) => {
    //       item.id === id;
    //     });
    //     console.log(q);
    //     if (q) {
    //       q.isPublished = true;
    //     }
    //   }),
    // );
    // console.log(questionList);
  };
  const skeletonNum = 5;
  // const [x, y] = useMouse();

  const LoadDom = () => {
    return <div ref={loadRef}>加载更多</div>;
  };
  return (
    <div className={style.container} ref={containerRef}>
      <Title level={3}>问卷调查</Title>
      <SearchInput></SearchInput>

      <Spin spinning={loading}>
        {/* {骨架屏} */}
        {loading &&
          Array.from({ length: skeletonNum }, () => <Skeleton active />)}
        {questionList.length === 0 && <div>暂无数据</div>}
        {questionList.map((item, index) => {
          return (
            <Card
              key={item.id}
              id={item?.id}
              state={item?.published}
              isPublished={item?.published}
              title={item?.title}
              isStar={item?.isStar}
              delQuestionList={delQuestionList}
              editQuestionList={edit}
              handStar={handStar}
            ></Card>
          );
        })}
      </Spin>
      <Button onClick={add} danger>
        新增问卷
      </Button>

      {/* <div>
        {x},{y}
      </div> */}
      <LoadDom></LoadDom>
    </div>
  );
};
export default List;
